package com.sx.manage.service.consumer;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.sx.common.util.http.HttpPoolManager;
import com.sx.common.util.http.model.HttpResult;
import com.sx.common.util.type.ContentType;
import com.sx.manage.biz.consumer.IMConsumerEditLogDetailBiz;
import com.sx.manage.biz.consumer.bank.IMConsumerBankMapBiz;
import com.sx.manage.biz.consumer.info.IMNetworkPersonConsumerBiz;
import com.sx.manage.service.bank.IMBaseConsumerBankMapService;
import com.sx.manage.service.consumer.info.IMConsumerOperationInfoService;
import com.sx.manage.service.consumer.util.WebConsumerEditUtil;
import com.sx.manage.servlet.ViewAndModel;
import com.sx.model.constants.MSystemConstants;
import com.sx.model.constants.type.FieldConstants;
import com.sx.model.constants.type.bank.MOutCardType;
import com.sx.model.constants.type.consumer.MConsumerEditFieldType;
import com.sx.model.constants.type.consumer.MInfoEditApplyStatus;
import com.sx.model.manage.mybatis.form.consumer.edit.MConsumerEditLogDetailForm;
import com.sx.model.manage.mybatis.vo.consumer.MConsumerBankMapVO;
import com.sx.model.manage.mybatis.vo.consumer.MConsumerEditDetailVO;
import com.sx.model.manage.mybatis.vo.consumer.MConsumerEditLogDetailVO;
import com.sx.model.manage.mybatis.vo.consumer.login.MConsumerLoginVO;
import com.sx.model.manage.mybatis.vo.result.ResultBooleanVO;
import com.sx.model.manage.mybatis.vo.result.ResultListVO;

/**
 * 个人用户信息
 * 
 * @author lenovo
 *
 */
@Service("personConsumerEditWebServiceImpl")
public class MPersonConsumerEditWebServiceImpl {

	private Logger log = LoggerFactory.getLogger(this.getClass());

	// 用户信息新接口
	@Resource(name = "mNetworkPersonConsumerBizImpl")
	public IMNetworkPersonConsumerBiz mNetworkPersonConsumerBizImpl;
	// 用户信息修改
	@Resource(name = "consumerEditInfoServiceImpl")
	private IMConsumerEditInfoService consumerEditInfoServiceImpl;
	// /修改详细明细service
	@Resource
	private IMConsumerEditLogDetailBiz consumerEditLogDetailBizImpl;
	// 扩展信息
	@Resource(name = "consumerOperationInfoServiceImpl")
	private IMConsumerOperationInfoService consumerOperationInfoServiceImpl;
	// http 连接池
	@Resource(name = "httppoolmanager")
	public HttpPoolManager httpPoolManager;
	
	@Resource(name = "mConsumerBankMapBizImpl")
	private IMConsumerBankMapBiz mConsumerBankMapBizImpl;
	// 用户银行信息
	@Resource
	private IMBaseConsumerBankMapService mBaseConsumerBankMapServiceImpl;
	public ViewAndModel editInfoDetail(Long id, ViewAndModel model) {
		log.info("修改信息详细界面id={}",id);
		model.setViewName("consumer/auditing/infordetail");
		
		model.addObject("edit_log_id", id);
		return model;
	}

	/** 查询详细信息修改数据 **/
	public ResultListVO<MConsumerEditDetailVO> editInfoDetailData(MConsumerEditLogDetailForm form) {
		log.info("查询详细信息修改数据form={}",form);
		return consumerEditLogDetailBizImpl.queryListForAuth(form);
	}

	/** 查询详细信息修改数据 过时 因为华夏界面不存在 **/
	public ResultListVO<MConsumerEditDetailVO> editInfoDetailForHuaXiaData(MConsumerEditLogDetailForm form) {
		
		ResultListVO<MConsumerEditDetailVO> result = consumerEditLogDetailBizImpl.queryListForAuth(form);
		List<MConsumerEditDetailVO> dataList = result.getData();
		List<MConsumerEditDetailVO> returnList = WebConsumerEditUtil.editInfoDetailForHuaXiaData(dataList);

		result.setData(returnList);
		return result;
	}

	/**
	 * 用户修改申请状态修改及相应的逻辑处理
	 * 
	 * @param MConsumerLoginVO
	 * @param loginUser
	 * @return
	 */
	public ResultBooleanVO consumer_edit_status(MConsumerEditLogDetailForm detailForm, MConsumerLoginVO loginSysUser) {
		log.debug("用户信息修改 consumer_edit_status 分发");
		// 完成状态下，查询需要修改的用户数据
		MConsumerEditLogDetailVO editVO = null;
		if (MInfoEditApplyStatus.EDIT_FINISH.equals(detailForm.getEdit_status())) {
			log.info("完成状态，获取用户修改数据edit_detail_id={}",detailForm.getId());
			editVO = consumerEditLogDetailBizImpl.queryById(detailForm.getId()).getObjVo();
		}
		ResultBooleanVO result = null;
		try {
			MConsumerEditLogDetailVO editDetailVO = consumerEditLogDetailBizImpl.queryById(detailForm.getId()).getObjVo();
			// 系统审核通过
			log.info("后台审核id={},edit_status={}",detailForm.getId(),detailForm.getEdit_status());
			if (MInfoEditApplyStatus.EDIT_PASS_MANAGE.equals(detailForm.getEdit_status())) {
				log.info("后台通过操作id={},edit_status={}",detailForm.getId(),detailForm.getEdit_status());
				detailForm.setRemark(detailForm.getEdit_status().getDescription());
				log.info("detailForm={}",detailForm);
				if (!MInfoEditApplyStatus.EDIT_PASS.equals(editDetailVO.getEdit_status())) {
					log.info("数据公司端没有审核，后台不能审核 detail_id={}", detailForm.getId());
					return new ResultBooleanVO("sx.m.consumer.edit.detail.status.is.not.pass");
				}
				
			}
			if (MInfoEditApplyStatus.EDIT_NO_PASS.equals(detailForm.getEdit_status())) {
				log.info("不通过操作bid={},edit_status={}",detailForm.getId(),detailForm.getEdit_status());
				if (StringUtils.isNotBlank(detailForm.getRemark())) {
					detailForm.setRemark("平台审核不通过:" + detailForm.getRemark());
				} else {
					detailForm.setRemark("平台审核不通过");
				}
				log.info("detailForm={}",detailForm);
				if (!MInfoEditApplyStatus.EDIT_PASS.equals(editDetailVO.getEdit_status()) && !MInfoEditApplyStatus.EDIT_PASS_MANAGE.equals(editDetailVO.getEdit_status())) {
					log.info("数据公司端与系统都没有审核通过，系统不能审核 detail_id={}", detailForm.getId());
					return new ResultBooleanVO("sx.m.consumer.edit.detail.status.is.not.pass");
				}
			}
			if (MInfoEditApplyStatus.EDIT_FINISH.equals(detailForm.getEdit_status())) {
				log.info("完成操作bid={},edit_status={}",detailForm.getId(),detailForm.getEdit_status());
				detailForm.setRemark("完成");
				log.info("detailForm={}",detailForm);
				if (!MInfoEditApplyStatus.EDIT_PASS_MANAGE.equals(editDetailVO.getEdit_status())) {
					log.info("数据公司端没有审核，后台不能审核 detail_id={}", detailForm.getId());
					return new ResultBooleanVO("sx.m.consumer.edit.detail.status.is.not.pass");
				}
			}
			// 备注为空，写入状态中文提示
			if (StringUtils.isBlank(detailForm.getRemark())) {
				detailForm.setRemark(detailForm.getEdit_status().getDescription());
			}
			log.info("detailForm={}",detailForm);
			if(MInfoEditApplyStatus.EDIT_FINISH.equals(detailForm.getEdit_status())) {
				log.info("完成状态，查看是银行字段修改detailForm={}",detailForm);
				//如果是银行卡信息修改，走新的流程
				switch(String.valueOf(editDetailVO.getEdit_field_english())) {
					case FieldConstants.CONSUMER_BANK_BANK_CONSUMER_NAME:
						result = bankUpdateForFinish(editDetailVO,detailForm, loginSysUser);
						break;
					case FieldConstants.CONSUMER_BANK_BANK_ID:
						result = bankUpdateForFinish(editDetailVO,detailForm, loginSysUser);
						break;
					case FieldConstants.CONSUMER_BANK_BANK_NAME:
						result = bankUpdateForFinish(editDetailVO,detailForm, loginSysUser);
						break;
					case FieldConstants.CONSUMER_BANK_CARD_NUM:
						result = bankUpdateForFinish(editDetailVO,detailForm, loginSysUser);
						break;
					case FieldConstants.CONSUMER_BANK_CITY_ID:
						result = bankUpdateForFinish(editDetailVO,detailForm, loginSysUser);
						break;
					case FieldConstants.CONSUMER_BANK_CITY_NAME:
						result = bankUpdateForFinish(editDetailVO,detailForm, loginSysUser);
						break;
					case FieldConstants.CONSUMER_BANK_CLS_BANK_CODE:
						result = bankUpdateForFinish(editDetailVO,detailForm, loginSysUser);
						break;
					case FieldConstants.CONSUMER_BANK_CLS_BANK_NAME:
						result = bankUpdateForFinish(editDetailVO,detailForm, loginSysUser);
						break;
					default:
						result = consumerEditLogDetailBizImpl.editStatus(detailForm, loginSysUser); 
							break;
				}
			}else {
				log.info("不是完成状态，直接审核数据detailForm={}",detailForm);
				result = consumerEditLogDetailBizImpl.editStatus(detailForm, loginSysUser);
			}
			
		} catch (Exception ex) {
			log.error("修改用户申请状态异常error={}", ex);
			return new ResultBooleanVO(false, null, "操作失败");
		}
		if (!result.isSuccess()) {
			log.info("用户修改申请状态修改失败error={}", result.getMsg());
			return result;
		}
		log.info("用户修改申请状态修改成功，开始判断是否T用户下线");
		if (null != editVO) {
			// 踢人下线
			result = kickLoginConsumer(editVO);
			if (!result.isSuccess()) {
				result.setMsg("修改信息完成，但是踢人下线失败");
				return result;
			}
		}
		return result;
	}
	/** 修改银行卡新流程 **/
	private ResultBooleanVO bankUpdateForFinish(MConsumerEditLogDetailVO editDetailVO,MConsumerEditLogDetailForm detailForm, MConsumerLoginVO loginSysUser) {
		log.info("审核修改的时银行卡数据editDetailVO={},detailForm={}",editDetailVO,detailForm);
		ResultBooleanVO result = null;
		MConsumerBankMapVO bankMapVO = mBaseConsumerBankMapServiceImpl.query_consumerBankMap_for_manage(editDetailVO.getConsumer_id(), null);
		if(null==bankMapVO) {
			return new ResultBooleanVO(false,null,"用户没有设置默认银行卡");
		}else {
			if(MOutCardType.OUT_CARD_ONE.equals(bankMapVO.getOut_card_type())
					||MOutCardType.OUT_CARD_TWO.equals(bankMapVO.getOut_card_type())
					||MOutCardType.OUT_CARD_THREE.equals(bankMapVO.getOut_card_type())){
				return new ResultBooleanVO(false, null, "用户现在是绑卡状态，不能修改银行信息，请先解绑");
			}
		}
		//如果是银行卡信息修改，走新的流程
		switch(String.valueOf(editDetailVO.getEdit_field_english())) {
			case FieldConstants.CONSUMER_BANK_BANK_ID:
				result = consumerEditLogDetailBizImpl.editStatus(detailForm, loginSysUser); 
				break;
			case FieldConstants.CONSUMER_BANK_BANK_NAME:
				result = consumerEditLogDetailBizImpl.editStatus(detailForm, loginSysUser); 
				break;
			case FieldConstants.CONSUMER_BANK_CITY_ID:
				result = consumerEditLogDetailBizImpl.editStatus(detailForm, loginSysUser); 
				break;
			case FieldConstants.CONSUMER_BANK_CITY_NAME:
				result = consumerEditLogDetailBizImpl.editStatus(detailForm, loginSysUser); 
				break;
			case FieldConstants.CONSUMER_BANK_CLS_BANK_CODE:
				result = consumerEditLogDetailBizImpl.editStatus(detailForm, loginSysUser); 
				break;
			case FieldConstants.CONSUMER_BANK_CLS_BANK_NAME:
				result = consumerEditLogDetailBizImpl.editStatus(detailForm, loginSysUser); 
				break;
			default:
				result = consumerEditLogDetailBizImpl.editStatus(detailForm, loginSysUser); 
					break;
		}
		log.info("审核完成editDetailVO={},detailForm={}",editDetailVO,detailForm);
		return result;
	}

	/** 用户修改申请状态修改及相应的逻辑处理(华夏使用) */
	public ResultBooleanVO consumer_edit_status_for_huaxia(Long detail_id, MInfoEditApplyStatus editStatus, MConsumerLoginVO loginSysUser) {
		log.debug("用户信息修改 consumer_edit_status_for_huaxia detail_id={}", detail_id);
		// 完成状态下，查询需要修改的用户数据
		MConsumerEditLogDetailVO editVO = null;
		if (MInfoEditApplyStatus.EDIT_FINISH.equals(editStatus)) {
			editVO = consumerEditLogDetailBizImpl.queryById(detail_id).getObjVo();
		}
		// 修改数据状态
		MConsumerEditLogDetailForm detailForm = new MConsumerEditLogDetailForm();
		detailForm.setId(detail_id);
		detailForm.setEdit_status(editStatus);
		ResultBooleanVO result = null;
		try {
			MConsumerEditLogDetailVO editDetailVO = consumerEditLogDetailBizImpl.queryById(detailForm.getId()).getObjVo();
			if (!MInfoEditApplyStatus.EDIT_PASS_MANAGE.equals(editDetailVO.getEdit_status())) {
				log.info("后台没有审核，不能审核 detail_id={}", detailForm.getId());
				return new ResultBooleanVO("sx.m.consumer.edit.detail.status.is.not.pass");
			}
			detailForm.setRemark("完成");
			result = consumerEditLogDetailBizImpl.editStatus(detailForm, loginSysUser);
		} catch (Exception ex) {
			log.error("修改用户申请状态异常error={}", ex);
			return new ResultBooleanVO(false, null, "操作失败");
		}
		if (!result.isSuccess()) {
			log.info("用户修改申请状态修改失败error={}", result.getMsg());
			return result;
		}
		log.info("用户修改申请状态修改成功，开始判断是否T用户下线");
		if (null != editVO) {
			// 踢人下线
			result = kickLoginConsumer(editVO);
			if (!result.isSuccess()) {
				result.setMsg("修改信息完成，但是踢人下线失败");
				return result;
			}
		}
		return result;
	}

	/** 用户修改邮箱、手机号，踢人下线 **/
	private ResultBooleanVO kickLoginConsumer(MConsumerEditLogDetailVO detailVO) {
		boolean offline = false;
		if (MConsumerEditFieldType.EMAIL.equals(detailVO.getEdit_field_english())) {
			log.info("用户修改邮箱consumer={},email={}踢人下线", detailVO.getConsumer_id(), detailVO.getNew_value());
			offline = true;
		}
		if (MConsumerEditFieldType.MOBILE_TEL.equals(detailVO.getEdit_field_english())) {
			log.info("用户修改邮箱consumer={},mobile_tel={}踢人下线", detailVO.getConsumer_id(), detailVO.getNew_value());
			offline = true;
		}
		if (offline) {
			log.info("踢人下线consumerId",detailVO.getConsumer_id());
			return offline(detailVO.getConsumer_id());
		}
		return new ResultBooleanVO();
	}

	/** 踢人下线失败 **/
	private ResultBooleanVO offline(Long user_id) {
		String url_web = MSystemConstants.PERSON_WEB_URL;
		String url_logout = MSystemConstants.PERSON_WEB_URL_LOGOUT;
		StringBuilder message = new StringBuilder();
		message.append("{\"user_id\":").append(user_id).append("}");
		try {
			log.info("踢人下线http地址 url={}", (url_web + url_logout));
			HttpResult httpResult = httpPoolManager.getHttpClient().postAuthorization(url_web + url_logout, ContentType.JSON, null, MConsumerWebServiceImpl.HTTP_TIME_OUT, message.toString(), "UTF-8");
			if (null == httpResult || 200 != httpResult.getStatus()) {
				log.error("修改信息完成，但是踢人下线失败user_id={}", user_id);
				return new ResultBooleanVO(false, null, "修改信息完成，但是踢人下线失败");
			}
		} catch (Exception e) {
			log.error("http请求踢人下线异常error={}", e);
		}
		return new ResultBooleanVO();
	}

}
